﻿using Models;
using Scheduledscheduling.Models.TaskOptionsShow;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Timers;
using System.Reflection;

namespace Scheduledscheduling
{
    public partial class Main : Form
    {
        

        public static List<TaskOptionsShow> timers = new List<TaskOptionsShow>();
        private readonly User use;
        public Main(User use)
        {
            this.use = use;
            this.WindowState= FormWindowState.Maximized;
            InitializeComponent();
            dataGridView1.ReadOnly = true;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.RowHeadersVisible = false;
            this.FormClosed += new FormClosedEventHandler(frm_FormClosed);
            if (use.UserType == 1)
            {
                this.Text = $"管理员【{use.UserName}】";
            }
            else
            {
                this.Text = $"游客【{use.UserName}】";
            }


        }

        private void frm_FormClosed(object sender, FormClosedEventArgs e)
        {
            frm_verify frm = new frm_verify(use);
            frm.ShowDialog();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void Initialization(TaskOptionsShow p)
        {
            var presentTime = DateTime.Now;
            if (use.UserType == 1)
            {
                if (p.Status == 1)
                {
                    if (p.TaskTimer == null)
                    {
                        p.TaskTimer = new System.Timers.Timer();
                    }
                    double seconds = (p.Interval * 60);
                    p.TaskTimer.Enabled = false;
                    p.TaskTimer.Interval = seconds * 1000;//换算毫秒
                    p.TaskTimer.Elapsed += new ElapsedEventHandler((s, ex) => Timer_Elapsed(s, ex, p));
                    p.TaskTimer.Enabled = true;
                    p.TaskTimer.Start();
                }
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void GetTaskOps()
        {
        
            var taskList = new List<TaskOptionsShow>();
            var dbTaskList = Sugar.db.Queryable<TaskOptions>().ToList();
            foreach (var m in dbTaskList)
            {
                string statusDesc;
                switch (m.Status)
                {
                    case (int)Models.TaskOptionsShow.Status.Working:
                        statusDesc = "待运行";
                        break;
                    case (int)Models.TaskOptionsShow.Status.Run:
                        statusDesc = "运行";
                        if (!timers.Any(it => it.TaskName == m.TaskName && it.GroupName == m.GroupName && it.Id == m.Id))
                        {
                            var om = new TaskOptionsShow
                            {
                                Id = m.Id,
                                TaskName = m.TaskName,
                                GroupName = m.GroupName,
                                Interval = m.Interval,
                                ApiUrl = m.ApiUrl,
                                RequestType = m.RequestType,
                                Status = m.Status,
                                StatusDesc = "运行",
                                AuthKey = m.AuthKey,
                                AuthValue = m.AuthValue,
                                Describe = m.Describe,
                                LastRunTime = m.LastRunTime != default ? m.LastRunTime : DateTime.Now
                            };
                            timers.Add(om);
                        }
                        break;
                    case (int)Models.TaskOptionsShow.Status.Execute:
                        statusDesc = "立即执行";
                        break;
                    case (int)Models.TaskOptionsShow.Status.Stop:
                        statusDesc = "暂停";
                        break;
                    default:
                        statusDesc = "未知";
                        break;
                }

                var show = new TaskOptionsShow
                {
                    Id = m.Id,
                    TaskName = m.TaskName,
                    GroupName = m.GroupName,
                    Interval = m.Interval,
                    ApiUrl = m.ApiUrl,
                    RequestType = m.RequestType,            
                    Status = m.Status,
                    StatusDesc = statusDesc,
                    Describe = m.Describe,
                    LastRunTime = m.LastRunTime,
                    AuthKey = m.AuthKey,
                    AuthValue = m.AuthValue
                };
                taskList.Add(show);
            }
            dataGridView1.Invoke(new Action(() =>
            {
                var dt = HttpReuestUtility.List2DataTable(taskList);       
                dataGridView1.DataSource = dt;
                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
                dataGridView1.AllowUserToAddRows = false;
                dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            }));
            foreach (var p in timers.Where(t => t.Status == (int)Models.TaskOptionsShow.Status.Run))
            {
                if (p.TaskTimer == null || !p.TaskTimer.Enabled)
                {
                    Initialization(p);
                }
            }
        }


        private void Timer_Elapsed(object sender, ElapsedEventArgs e, TaskOptionsShow p)
        {
            var dateTime = DateTime.Now;
            var op = new TaskOptions        
            {
                Id = p.Id,
                TaskName = p.TaskName,
                GroupName = p.GroupName,
                Interval = p.Interval,
                ApiUrl = p.ApiUrl,
                AuthKey = p.AuthKey,
                AuthValue = p.AuthValue,
                Describe = p.Describe,
                RequestType = p.RequestType,
                LastRunTime = p.LastRunTime,
                Status = p.Status,
            };
            GetUrlAdd(op, dateTime);
        }
        private static readonly SnowflakeIdGenerator SnowflakeIdGenerator = new SnowflakeIdGenerator(1, 1);

      
        private bool GetUrlAdd(TaskOptions op, DateTime dateTime)
        {
            var result = false;
            try
            {
                var httpMessage = op.RequestType?.ToLower() == "get" ? HttpReuestUtility.GetResponseDataByGet(op.ApiUrl) : HttpReuestUtility.GetResponseDataByPost(op);

                var resultModel = new TaskLog
                {
                    Id = SnowflakeIdGenerator.NextId(),
                    GroupName = op.GroupName,
                    TaskName = op.TaskName,
                    Msg = string.IsNullOrEmpty(httpMessage) ? "OK" : httpMessage.ToString(),
                    BeginDate = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    EndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                };
                op.LastRunTime = Convert.ToDateTime(resultModel.EndDate);
                Sugar.db.GetSimpleClient<TaskOptions>().Update(op);
                Sugar.db.GetSimpleClient<TaskLog>().Insert(resultModel);
                if (!string.IsNullOrWhiteSpace(httpMessage))
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                var log = new TaskLog
                {
                    Id = SnowflakeIdGenerator.NextId(),
                    GroupName = op.GroupName,
                    TaskName = op.TaskName,
                    BeginDate = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    EndDate = op.LastRunTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    Msg = ex.Message
                };
                Sugar.db.GetSimpleClient<TaskLog>().Insert(log);
                throw ex;
            }

            // 立即刷新UI数据源       
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));

            return result;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (use.UserType == 1)
            {
                Modify frm = new Modify(null);
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("权限不够，请用管理员操作");
            }
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (use.UserType == 1)
            {
                DataGridViewRow row = dataGridView1.SelectedRows[0];
                if (!row.Selected)
                {
                    MessageBox.Show("请选中需要修改的数据");
                }
                var Status = 0;
                switch (row.Cells["StatusDesc"].Value)
                {
                    case "待运行":
                        Status = 0;
                        break;
                    case "运行":
                        Status = 1;
                        break;
                    case "立即执行":
                        Status = 2;
                        break;
                    case "暂停":
                        Status = 3;
                        break;
                }
                if (Status == (int)Models.TaskOptionsShow.Status.Stop)
                {
                    var op = new TaskOptions
                    {
                        Id = (int)row.Cells["Id"].Value,
                        TaskName = row.Cells["TaskName"].Value.ToString(),
                        GroupName = row.Cells["GroupName"].Value.ToString(),
                        Interval = (int)row.Cells["Interval"].Value,
                        ApiUrl = row.Cells["ApiUrl"].Value.ToString(),
                        RequestType = row.Cells["RequestType"].Value.ToString(),
                        Status = Status,
                        Describe = row.Cells["Describe"].Value.ToString(),
                    };
                    if (op.RequestType == "POST")
                    {
                        op.AuthKey = row.Cells["AuthKey"].Value.ToString();
                        op.AuthValue = row.Cells["AuthValue"].Value.ToString();
                    }
                    Modify frm = new Modify(op);
                    frm.ShowDialog();
                }
                else
                {
                    MessageBox.Show("请先暂停需要修改的数据");
                }
            }
            else
            {
                MessageBox.Show("权限不够，请用管理员操作");
            }
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (use.UserType == 1)
            {
                DataGridViewRow row = dataGridView1.SelectedRows[0];
                if (!row.Selected)
                {
                    MessageBox.Show("请选中需要暂停的数据");
                }
                var op = new TaskOptions
                {
                    Id = (int)row.Cells["Id"].Value,
                    TaskName = row.Cells["TaskName"].Value.ToString(),
                    GroupName = row.Cells["GroupName"].Value.ToString(),
                    Interval = (int)row.Cells["Interval"].Value,
                    ApiUrl = row.Cells["ApiUrl"].Value.ToString(),
                    RequestType = row.Cells["RequestType"].Value.ToString(),
                    Status = (int)Models.TaskOptionsShow.Status.Stop,
                    Describe = row.Cells["Describe"].Value?.ToString()
                };
                if (op.RequestType == "POST")
                {
                    op.AuthKey = row.Cells["AuthKey"].Value.ToString();
                    op.AuthValue = row.Cells["AuthValue"].Value.ToString();
                }

                if (Sugar.db.GetSimpleClient<TaskOptions>().Update(op))
                {
                    for (int i = 0; i < timers.Count; i++)
                    {
                        if (timers[i].TaskName == op.TaskName && timers[i].GroupName == op.GroupName && timers[i].Id == op.Id)
                        {
                            if (timers[i].TaskTimer != null)
                            {
                                timers[i].TaskTimer.Enabled = false;
                                timers[i].Status = op.Status;
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("暂停失败");
                }
            }
            else
            {
                MessageBox.Show("权限不够，请用管理员操作");
            }
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (use.UserType == 1)
            {
                var presentTime = DateTime.Now;
                DataGridViewRow row = dataGridView1.SelectedRows[0];
                if (!row.Selected)
                {
                    MessageBox.Show("请选中需要开启的数据");
                    return;
                }
                var op = new TaskOptions
                {
                    Id = (int)row.Cells["Id"].Value,
                    TaskName = row.Cells["TaskName"].Value.ToString(),
                    GroupName = row.Cells["GroupName"].Value.ToString(),
                    Interval = (int)row.Cells["Interval"].Value,
                    ApiUrl = row.Cells["ApiUrl"].Value.ToString(),
                    RequestType = row.Cells["RequestType"].Value.ToString(),
                    Status = (int)Models.TaskOptionsShow.Status.Run,
                    Describe = row.Cells["Describe"].Value?.ToString()
                };
                if (op.RequestType == "POST")
                {
                    op.AuthKey = row.Cells["AuthKey"].Value.ToString();
                    op.AuthValue = row.Cells["AuthValue"].Value.ToString();
                }
                op.LastRunTime = DateTime.Now;

                var model = timers.FirstOrDefault(p => p.Id == op.Id);
                if (model == null)
                {
                    var o = new TaskOptionsShow
                    {
                        Id = op.Id,
                        TaskName = op.TaskName,
                        GroupName = op.GroupName,
                        Interval = op.Interval,
                        ApiUrl = op.ApiUrl,
                        Describe = op.Describe,
                        RequestType = op.RequestType,
                        LastRunTime = op.LastRunTime,
                        Status = op.Status,
                        StatusDesc = "运行",
                    };
                    if (op.RequestType == "POST")
                    {
                        o.AuthKey = op.AuthKey;
                        o.AuthValue = op.AuthValue;
                    }
                    timers.Add(o);
                }
                else
                {
                    model.Status = op.Status;
                    model.StatusDesc = "运行";
                    model.LastRunTime = op.LastRunTime;
                    model.Interval = op.Interval;
                    model.ApiUrl = op.ApiUrl;
                    model.RequestType = op.RequestType;
                    model.Describe = op.Describe;
                    if (op.RequestType == "POST")
                    {
                        model.AuthKey = op.AuthKey;
                        model.AuthValue = op.AuthValue;
                    }

                    timers[timers.FindIndex(p => p.Id == op.Id)] = model;
                }

                if (!Sugar.db.GetSimpleClient<TaskOptions>().Update(op))
                {
                    MessageBox.Show("开启失败");
                }
            }
            else
            {
                MessageBox.Show("权限不够，请用管理员操作");
            }
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (use.UserType == 1)
            {
                DataGridViewRow row = dataGridView1.SelectedRows[0];
                if (!row.Selected)
                {
                    MessageBox.Show("请选中需要删除的数据");
                    return;
                }
                var Status = 0;
                switch (row.Cells["StatusDesc"].Value)
                {
                    case "待运行":
                        Status = (int)Models.TaskOptionsShow.Status.Working;
                        break;
                    case "运行":
                        Status = (int)Models.TaskOptionsShow.Status.Run;
                        break;
                    case "立即执行":
                        Status = (int)Models.TaskOptionsShow.Status.Execute;
                        break;
                    case "暂停":
                        Status = (int)Models.TaskOptionsShow.Status.Stop;
                        break;
                }
                if (Status == (int)Models.TaskOptionsShow.Status.Stop)
                {
                    var op = new TaskOptions
                    {
                        Id = (int)row.Cells["Id"].Value,
                    };
                    if (Sugar.db.GetSimpleClient<TaskOptions>().Delete(op))
                    {
                        var model = timers.Where(it => it.Id == op.Id).FirstOrDefault();
                        if (model != null)
                        {
                            model.TaskTimer.Elapsed -= new ElapsedEventHandler((s, ex) => Timer_Elapsed(s, ex, null));
                            model.TaskTimer.Stop();
                            model.TaskTimer.Dispose();
                            timers.Remove(model);
                        }
                    }
                    else
                    {
                        MessageBox.Show("删除失败");
                    }
                }
                else
                {
                    MessageBox.Show("请选中数据暂停操作");
                    return;
                }
            }
            else
            {
                MessageBox.Show("权限不够，请用管理员操作");
            }
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void Main_SizeChanged(object sender, EventArgs e)
        {
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
        }

        private void button7_Click(object sender, EventArgs e)
        {
            DateTime dateTime = DateTime.Now;
            DataGridViewRow row = dataGridView1.SelectedRows[0];
            if (!row.Selected)
            {
                MessageBox.Show("请选中需要删除的数据");
                return;
            }
            var op = new TaskOptions
            {
                Id = (int)row.Cells["Id"].Value,
                TaskName = row.Cells["TaskName"].Value.ToString(),
                GroupName = row.Cells["GroupName"].Value.ToString(),
                Interval = (int)row.Cells["Interval"].Value,
                ApiUrl = row.Cells["ApiUrl"].Value.ToString(),
                RequestType = row.Cells["RequestType"].Value.ToString(),
                Status = (int)Models.TaskOptionsShow.Status.Execute,
                AuthKey = row.Cells["AuthKey"].Value?.ToString(),
                AuthValue = row.Cells["AuthValue"].Value?.ToString(),
                Describe = row.Cells["Describe"].Value?.ToString(),
            };
            GetUrlAdd(op, dateTime);
            dataGridView1.Invoke(new Action(() =>
            {
                GetTaskOps();
            }));
            MessageBox.Show("立即执行成功");
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var columnName = dataGridView1.Columns[e.ColumnIndex].Name;
            if (columnName != "btn")
            {
                return;
            }

            DateTime dateTime = DateTime.Now;
            DataGridViewRow row = dataGridView1.SelectedRows[0];
            if (!row.Selected)
            {
                MessageBox.Show("请选中需要删除的数据");
                return;
            }
            var op = new TaskOptions
            {
                Id = (int)row.Cells["Id"].Value,
                TaskName = row.Cells["TaskName"].Value.ToString(),
                GroupName = row.Cells["GroupName"].Value.ToString(),
                Interval = (int)row.Cells["Interval"].Value,
                ApiUrl = row.Cells["ApiUrl"].Value.ToString(),
                RequestType = row.Cells["RequestType"].Value.ToString(),
            };
            frm_TaskLstLog frm = new frm_TaskLstLog(op);
            frm.ShowDialog();
        }
    }
}
